<template>
  <el-upload :action="uploadImgUrl" multiple list-type="picture-card" ref="imageUpload" :on-remove="handleDelete"
    :class="{ hide: fileList.length >= limit }" :headers="headers" :limit="limit" :file-list="fileList"
    :before-upload="handleBeforeUpload" :on-error="handleUploadError" :on-exceed="handleExceed"
    :on-success="handleUploadSuccess" :on-preview="handlePictureCardPreview">
    <el-icon>
      <Plus />
    </el-icon>
    <template #tip>
      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip" v-if="isShowTip">
        请上传
        <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
        <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
        的文件
      </div>
    </template>
  </el-upload>
  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, watch } from 'vue'
import router from '@/router/index'
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadFile } from 'element-plus'
const props = defineProps({
  modelValue: [String, Object, Array],
  // 图片数量限制
  limit: {
    type: Number,
    default: 5,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["png", "jpg", "jpeg"],
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  }
})
const emits = defineEmits(['input'])
const baseUrl = `${import.meta.env.VITE_APP_BASE_API}`
const uploadImgUrl = `${import.meta.env.VITE_APP_BASE_API}/common/upload` // 上传的图片服务器地址
const headers = {
  Authorization: localStorage.getItem('token'),
}
const imageUpload = ref<null | HTMLElement>(null)
const dialogImageUrl = ref<string | undefined>('')
const dialogVisible = ref(false)
const disabled = ref(false)
const fileList = ref<any>([])
const number = ref<number>(0)
const uploadList = ref<any>([])
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      // 首先将值转为数组
      const list = Array.isArray(val) ? val : props.modelValue?.split(',');
      // 然后将数组转为对象数组
      fileList.value = list.map((item: string | string[]) => {
        if (typeof item === "string") {
          if (item.indexOf(baseUrl) === -1) {
            item = { name: baseUrl + item, url: baseUrl + item };
          } else {
            item = { name: item, url: item };
          }
        }
        return item;
      });
      sessionStorage.setItem('imgFileList', JSON.stringify(fileList.value))
    } else {
      fileList.value = [];
      return [];
    }
  },
  { deep: true, immediate: true }
);
const handleBeforeUpload = (file: any) => {
  let isImg = false;
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    isImg = props.fileType.some((type: any) => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  } else {
    isImg = file.type.indexOf("image") > -1;
  }

  if (!isImg) {
    ElMessage({
      message: `文件格式不正确, 请上传${props.fileType.join("/")}图片格式文件!`,
      type: 'error',
      duration: 2 * 1000
    })
    return false;
  }
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      ElMessage({
        message: `上传头像图片大小不能超过 ${props.fileSize} MB!`,
        type: 'error',
        duration: 2 * 1000
      })
      return false;
    }
  }
  // this.$modal.loading("正在上传图片，请稍候...");
  number.value++;
}
// 删除图片
function handleDelete(file: UploadFile) {
  if (sessionStorage.getItem('imgFileList')) {
    let imgFileList = JSON.parse(sessionStorage.getItem('imgFileList'))
    const findex = imgFileList.map((f: { name: string; }) => f.name).indexOf(file.name);
    if (findex > -1) {
      fileList.value.splice(findex, 1);
      emits('input', listToString(fileList.value))
    }
  }
}
// 上传失败
const handleUploadError = () => {
  ElMessage({
    message: "上传图片失败，请重试",
    type: 'error',
    duration: 2 * 1000
  })

}
const handleExceed = () => {
  ElMessage({
    message: `上传文件数量不能超过 ${props.limit} 个!`,
    type: 'error',
    duration: 2 * 1000
  })
}
const handleRemoveSingle = (file: UploadFile) => {
  console.log(file)
}
// 上传成功回调
const handleUploadSuccess = (res: any, file: UploadFile) => {
  if (res.code === 200) {
    // console.log(res);
    // console.log(file);
    // console.log(process.env.VUE_APP_BASE_API + '/' + res.file.filename);
    uploadList.value.push({ name: res.fileName, url: res.url });
    uploadedSuccessfully();
  } else {
    number.value--;
    // this.$modal.closeLoading();
    // this.$modal.msgError(res.msg);
    imageUpload.value.handleRemove(file);
    uploadedSuccessfully();
    if (res.code === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      ElMessageBox.confirm(
        '登录超时或者未登陆，您可以继续停留在该页面或者重新登录',
        '提示',
        {
          confirmButtonText: '登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        router.push('/login')
      })
    }
  }
}
// 上传结束处理
function uploadedSuccessfully() {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value.concat(uploadList.value);
    uploadList.value = [];
    number.value = 0;
    emits('input', listToString(fileList.value))
    // this.$modal.closeLoading();
  }
}
//对象转成指定字符串分隔
function listToString(list: { [x: string]: { url: string; }; }, separator?: string | undefined) {
  let strs = "";
  separator = separator || ",";
  for (let i in list) {
    if (list[i].url) {
      strs += list[i].url.replace(baseUrl, "") + separator;
    }
  }
  return strs != '' ? strs.substr(0, strs.length - 1) : '';
}
const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}
</script>
<style lang="scss" scoped>
.hide {
  :deep(.el-upload--picture-card) {
    display: none;
  }
}

// ::v-deep.hide .el-upload--picture-card {
//   display: none;
// }
</style>
